using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agriculture.Api.Read.Application.Command;
using Agriculture.Domain;
using Dapper;
using MediatR;
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System.Collections.Generic; // Added for List

namespace Agriculture.Api.Read.Application.Handler
{
    /// <summary>
    /// 药品订单详情查询处理器
    /// </summary>
    public class MedicineOrderDetailQueryHandler : IRequestHandler<MedicineOrderDetailQuery, MedicineOrderDetailResult>
    {
        private readonly IConfiguration _configuration;

        public MedicineOrderDetailQueryHandler(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<MedicineOrderDetailResult> Handle(MedicineOrderDetailQuery request, CancellationToken cancellationToken)
        {
            string connectionString = _configuration.GetConnectionString("DefaultConnection");

            using (var connection = new MySqlConnection(connectionString))
            {
                // 查询订单基本信息
                var orderSql = @"
                    SELECT o.OrderNo, o.TotalAmount AS OrderAmount, o.Status, o.CreateTime AS SubmitTime,
                           o.Receiver AS ReceiverName, o.ReceiverPhone AS ReceiverPhone, o.ReceiverAddress AS ReceiverAddress
                    FROM medicineordermodel o
                    WHERE o.OrderNo = @OrderNo AND o.IsDeleted = 0";

                var order = await connection.QueryFirstOrDefaultAsync<dynamic>(orderSql, new { OrderNo = request.OrderNo });

                if (order == null)
                {
                    return null;
                }

                var result = new MedicineOrderDetailResult
                {
                    OrderNo = order.OrderNo,
                    OrderAmount = order.OrderAmount,
                    Status = ConvertStatus(order.Status),
                    SubmitTime = order.SubmitTime,
                    Receiver = new ReceiverInfo
                    {
                        Name = order.ReceiverName,
                        Phone = order.ReceiverPhone,
                        Address = order.ReceiverAddress
                    }
                };

                // 查询订单药品信息
                var medicineSql = @"
                    SELECT m.Name, m.ImageUrl, om.Specification, om.Usage, om.Quantity
                    FROM ordermedicinemodel om
                    LEFT JOIN medicinemodel m ON om.MedicineId = m.Id
                    WHERE om.OrderNo = @OrderNo AND om.IsDeleted = 0";

                var medicines = await connection.QueryAsync<OrderMedicineInfo>(medicineSql, new { OrderNo = request.OrderNo });
                result.Medicines.AddRange(medicines);

                // 查询物流信息
                var logisticsSql = @"
                    SELECT l.LogisticsCompany AS Company, l.TrackingNumber
                    FROM logisticstrackingmodel l
                    WHERE l.OrderNo = @OrderNo AND l.IsDeleted = 0
                    LIMIT 1";

                var logistics = await connection.QueryFirstOrDefaultAsync<LogisticsInfo>(logisticsSql, new { OrderNo = request.OrderNo });
                
                if (logistics != null)
                {
                    result.Logistics = logistics;
                    //trackingNumber
                    // 查询物流跟踪记录
                    var trackingSql = @"
                        SELECT t.TrackingTime AS Time, t.TrackingContent AS Description
                        FROM logisticstrackingmodel t
                        WHERE t.TrackingNumber = @TrackingNumber AND t.IsDeleted = 0
                        ORDER BY t.TrackingTime DESC";

                    var trackingRecords = await connection.QueryAsync<LogisticsTrackingRecord>(
                        trackingSql, new { TrackingNumber = logistics.TrackingNumber });
                    
                    result.Logistics.TrackingRecords.AddRange(trackingRecords);
                }

                return result;
            }
        }

        /// <summary>
        /// 转换状态码为状态文本
        /// </summary>
        private string ConvertStatus(int status)
        {
            switch (status)
            {
                case 1:
                    return "待发货";
                case 2:
                    return "待收货";
                case 3:
                    return "已收货";
                default:
                    return "未知";
            }
        }
    }
} 